import { Directive, nextTick } from 'vue';

const scrollbarDirective: Directive = {
  bind(el) {
    nextTick(() => {
      checkScrollbar(el);
    });
    el.__judgeScrllBarHandler = function () {
      checkScrollbar(el);
    };
    window.addEventListener('resize', el.__judgeScrllBarHandler);
  },
  unbind(el) {
    window.removeEventListener('resize', el.__judgeScrllBarHandler);
    delete el.__judgeScrllBarHandler;
  },
  componentUpdated(el) {
    checkScrollbar(el);
  }
};

function checkScrollbar(el: HTMLElement) {
  const operate = el.scrollHeight > el.clientHeight ? 'add' : 'remove';
  el.classList[operate]('has-scrollbar');
}

export default scrollbarDirective;
